<!-- 题库管理 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="queryParams.keyword"
            placeholder="题目内容"
            clearable
          />
        </el-form-item>
        <el-form-item label="科目">
          <el-input
            v-model="queryParams.subject"
            placeholder="科目"
            clearable
          />
        </el-form-item>
        <el-form-item label="类型">
          <el-select
            v-model="queryParams.type"
            placeholder="题目类型"
            clearable
            style="width: 180px"
          >
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select
            v-model="queryParams.difficulty"
            placeholder="难度"
            clearable
            style="width: 180px"
          >
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
        <el-upload
          class="upload-button"
          :action="uploadUrl"
          :headers="headers"
          :on-success="handleImportSuccess"
          :on-error="handleImportError"
          :show-file-list="false"
        >
          <el-button type="success">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="info" @click="handleRemoveDuplicates">
          <el-icon><Delete /></el-icon>
          去重
        </el-button>
      </div>
    </div>

    <!-- 题目列表 -->
    <el-table
      v-loading="loading"
      :data="questionList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="questionType" label="类型" width="100">
        <template #default="{ row }">
          <el-tag :type="row.questionType === 'single' ? 'primary' : 'success'">
            {{ row.questionType === "single" ? "单选题" : "多选题" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="subject" label="科目" width="120" />
      <el-table-column
        prop="questionText"
        label="题目内容"
        show-overflow-tooltip
      />
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)">
            {{ row.difficulty }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="score" label="分值" width="80" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="questionFormRef"
        :model="questionForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="题目类型" prop="questionType">
          <el-select
            v-model="questionForm.questionType"
            placeholder="请选择题目类型"
            style="width: 180px"
          >
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
          </el-select>
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="questionForm.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="题目内容" prop="questionText">
          <el-input
            v-model="questionForm.questionText"
            type="textarea"
            rows="3"
            placeholder="请输入题目内容"
          />
        </el-form-item>
        <el-form-item label="选项" prop="options">
          <el-input
            v-model="questionForm.options"
            type="textarea"
            rows="4"
            placeholder="请输入选项，每个选项占一行，格式如：A. 选项内容"
          />
        </el-form-item>
        <el-form-item label="正确答案" prop="correctAnswer">
          <el-input
            v-model="questionForm.correctAnswer"
            placeholder="单选题填写选项字母，多选题用逗号分隔"
          />
        </el-form-item>
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="questionForm.score" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-select
            v-model="questionForm.difficulty"
            placeholder="请选择难度"
            style="width: 180px"
          >
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getQuestions,
  addQuestion,
  updateQuestion,
  deleteQuestion,
  exportQuestions,
  removeDuplicates,
} from "@/api/question";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  subject: "",
  type: "",
  difficulty: "",
});

// 题目列表数据
const loading = ref(false);
const questionList = ref([]);
const total = ref(0);
const selectedQuestions = ref([]); // 选中的题目

// 获取题目列表
const getQuestionList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getQuestions(queryParams);
    console.log(records);
    questionList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取题目列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getQuestionList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.keyword = "";
  queryParams.subject = "";
  queryParams.type = "";
  queryParams.difficulty = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getQuestionList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getQuestionList();
};

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = computed(() => (questionForm.id ? "编辑题目" : "新增题目"));
const questionFormRef = ref(null);
const questionForm = reactive({
  id: null,
  questionType: "",
  subject: "",
  questionText: "",
  options: "",
  correctAnswer: "",
  score: 1,
  difficulty: "",
});

// 表单校验规则
const rules = {
  questionType: [
    { required: true, message: "请选择题目类型", trigger: "change" },
  ],
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  questionText: [
    { required: true, message: "请输入题目内容", trigger: "blur" },
  ],
  options: [{ required: true, message: "请输入选项", trigger: "blur" }],
  correctAnswer: [
    { required: true, message: "请输入正确答案", trigger: "blur" },
  ],
  score: [{ required: true, message: "请输入分值", trigger: "blur" }],
  difficulty: [{ required: true, message: "请选择难度", trigger: "change" }],
};

// 重置表单
const resetForm = () => {
  questionForm.id = null;
  questionForm.questionType = "";
  questionForm.subject = "";
  questionForm.questionText = "";
  questionForm.options = "";
  questionForm.correctAnswer = "";
  questionForm.score = 1;
  questionForm.difficulty = "";
};

// 新增按钮点击
const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
};

// 编辑按钮点击
const handleEdit = (row) => {
  Object.assign(questionForm, row);
  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  if (!questionFormRef.value) return;
  await questionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (questionForm.id) {
          await updateQuestion(questionForm);
          ElMessage.success("更新成功");
        } else {
          await addQuestion(questionForm);
          ElMessage.success("添加成功");
        }
        dialogVisible.value = false;
        getQuestionList();
      } catch (error) {
        console.error("保存题目失败：", error);
      }
    }
  });
};

// 删除按钮点击
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该题目吗？", "提示", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteQuestion(row.id);
        ElMessage.success("删除成功");
        getQuestionList();
      } catch (error) {
        console.error("删除题目失败：", error);
      }
    })
    .catch(() => {});
};

// 表格选择改变
const handleSelectionChange = (selection) => {
  selectedQuestions.value = selection;
};

// 导出题目
const handleExport = async () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning("请选择要导出的题目");
    return;
  }
  try {
    const ids = selectedQuestions.value.map((item) => item.id);
    const response = await exportQuestions(ids);

    // 从响应头中获取文件名
    const contentDisposition = response.headers?.["content-disposition"];
    let filename = "questions.xlsx";
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename=(.*)/);
      if (filenameMatch) {
        filename = decodeURIComponent(filenameMatch[1]);
      }
    }

    // 创建Blob对象并下载
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出题目失败：", error);
    // 尝试解析错误信息
    if (error.response?.data instanceof Blob) {
      const text = await error.response.data.text();
      try {
        const errorData = JSON.parse(text);
        ElMessage.error(errorData.message || "导出失败");
      } catch (e) {
        ElMessage.error("导出失败");
      }
    } else {
      ElMessage.error("导出失败");
    }
  }
};

// 导入成功回调
const handleImportSuccess = () => {
  ElMessage.success("导入成功");
  getQuestionList();
};

// 导入失败回调
const handleImportError = () => {
  ElMessage.error("导入失败");
};

// 去重按钮点击
const handleRemoveDuplicates = async () => {
  try {
    await removeDuplicates();
    ElMessage.success("去重成功");
    getQuestionList();
  } catch (error) {
    console.error("去重失败：", error);
  }
};

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case "easy":
      return "success";
    case "medium":
      return "warning";
    case "hard":
      return "danger";
    default:
      return "info";
  }
};

// 上传相关
const uploadUrl = import.meta.env.VITE_API_URL + "/api/questions/import";
const headers = computed(() => ({
  Authorization: "Bearer " + localStorage.getItem("token"),
}));

onMounted(() => {
  getQuestionList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.upload-button {
  display: inline-block;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
